#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <stdio.h>
#include <errno.h>
#include <string.h>
int main()
{
    // socket(协议族，类型，0)
    int server_sockfd = socket(AF_INET, SOCK_STREAM, 0); 
    if (server_sockfd == -1) {
        fprintf(stderr, "error on socket errno=%d : %m\n", errno);
        return 1;
    }
    struct sockaddr_in server_sockaddr;
    bzero(&server_sockaddr, sizeof(server_sockaddr));
    //sin_family指代协议族，在socket编程中只能是AF_INET
    server_sockaddr.sin_family = AF_INET;
    //sin_port存储端口号（使用网络字节顺序）
    server_sockaddr.sin_port   = htons(8887);
    server_sockaddr.sin_addr.s_addr = inet_addr("10.172.198.86");
    if (bind(server_sockfd, (struct sockaddr*)&server_sockaddr, sizeof(server_sockaddr)) == -1) {
        fprintf(stderr, "error on bind errno=%d : %m\n", errno);
        return 1;
    }
    if (listen(server_sockfd, 5) != 0) {
        fprintf(stderr, "error on listen errno=%d : %m\n", errno);
        return 1;
    }
    for (;;) {
        fprintf(stdout, "listening...\n");
        struct sockaddr_in client_sockaddr;
        bzero(&client_sockaddr, sizeof(client_sockaddr));
        socklen_t length = sizeof(client_sockaddr);
        int client = accept(server_sockfd, (struct sockaddr*)&client_sockaddr, &length);
        if (client == -1) {
            fprintf(stderr, "error on accept errno=%d : %m\n", errno);
            continue;
        }
        fprintf(stdout, "recv data from client[%s:%d]...\n",
                inet_ntoa(client_sockaddr.sin_addr), ntohs(client_sockaddr.sin_port));
        for (;;) {
            char buffer[1024];
            memset(buffer,0,sizeof(buffer));
            int datalen = recv(client, buffer, sizeof(buffer), 0);
            if (strcmp(buffer, "bye\n") == 0) {
                break;
            }
            fprintf(stdout, "%s\n", buffer);
            send(client, buffer, datalen, 0);
        }
        close(client);
    }
    close(server_sockfd);
    return 0;
}
